package top.fzqblog.firstapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import top.fzqblog.music.util.MusicUtils;
import top.fzqblog.util.FileUtils;
import static top.fzqblog.utils.Constants.TAG;

/**
 * Created by 抽离 on 2017/10/7 0007.
 */

public class MusicTest extends AppCompatActivity {

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @OnClick({R.id.play, R.id.stop, R.id.pause, R.id.getMusic, R.id.netMusic})
    public void MediaControl(Button button){
        switch (button.getId()){
            case R.id.play:
                if(!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                }
                break;
            case R.id.stop:
                if(mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                break;
            case R.id.pause:
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                }
                break;
            case R.id.getMusic:
                getMusic();
                break;
            case R.id.netMusic:
                setSource("http://y.baidu.com/data/song/download?songId=200567");
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_layout);
        ButterKnife.bind(this);
    }

    private void getMusic(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        else{
            initMedia();
        }
    }

    private void initMedia() {
        Observable.OnSubscribe<File> observable = new Observable.OnSubscribe<File>() {
            @Override
            public void call(Subscriber<? super File> subscriber) {
                try {
//                    InputStream in = getAssets().open("少年夜雨行.mp3");
                    URL url = new URL("http://data.5sing.kgimg.com/G111/M01/19/04/rw0DAFmyczKAIr9IALdbuMYkITs055.mp3");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    InputStream in = httpURLConnection.getInputStream();
                    Log.i(TAG, "call: " + in.available());
                    File file = FileUtils.copyToDownloadFile(in, "樱花樱花想见你.mp3");
                    subscriber.onNext(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Observable
                .create(observable)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<File>() {
                    @Override
                    public void call(File file) {
                        Toast.makeText(MusicTest.this, "获取音乐" + file.getPath() + "文件大小"+file.length(), Toast.LENGTH_LONG).show();
                    }
                })
                .subscribe(file -> {
                     setSource(file.getPath());
                });
    }

    private void setSource(String path){
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            Toast.makeText(this, "音乐时长：" + MusicUtils.formatTime(mediaPlayer.getDuration()), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    initMedia();
                }
                else{
                    Toast.makeText(this, "没有读写权限无法播放！", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
        }
    }
}
